package com.frxuexi.sign.view

import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.MyLocationData
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.frxuexi.base.entity.SignBeanItem
import com.frxuexi.base.http.Const
import com.frxuexi.base.mvi.BaseActivity
import com.frxuexi.base.mvi.RequestType
import com.frxuexi.base.mvi.UiState
import com.frxuexi.base.utils.ArouterManager
import com.frxuexi.base.utils.DateTimeUtils
import com.frxuexi.sign.SignIntent
import com.frxuexi.sign.SignViewModel
import com.frxuexi.sign.databinding.ActivitySignBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask


@Route(path = "/sign/SignActivity")
@AndroidEntryPoint
class SignActivity : BaseActivity<ActivitySignBinding, SignIntent, SignViewModel>() {
    var timer: Timer? = null
    var mLocationClient: LocationClient? = null
    override fun getVM(): SignViewModel {
        return viewModels<SignViewModel>().value
    }

    override fun getBind(): ActivitySignBinding {
        return ActivitySignBinding.inflate(layoutInflater)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.DEFAULT->{
                                val items = it.data as Collection<SignBeanItem>
                                val list = items.filter {
                                    it.morningCheckIn.split(" ")[0] == DateTimeUtils.getDate(System.currentTimeMillis())
                                }
                                if(list.size>0){
                                    if(list.get(0).afternoonCheckIn.isNullOrEmpty()){//没打下班卡
                                        binding.signTvdaka.text="下班打卡"
                                    }else{//已经打了下班卡
                                        binding.btnSign.isEnabled=false
                                    }
                                }
                            }
                            RequestType.ADD->{
                                val item = it.data as SignBeanItem
                                SPUtils.getInstance().apply {
                                    put("sid",item.id!!)
                                    put("morning",item.morningCheckIn)
                                }
                            }

                            else -> {}
                        }

                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {

        lifecycleScope.launch(Dispatchers.IO) {
            timer = Timer()
            timer?.schedule(timerTask {
                val time = DateTimeUtils.getTime(System.currentTimeMillis())
                lifecycleScope.launch(Dispatchers.Main) {
                    binding.signTime.setText(time)
                }
            }, 0, 1000)
        }
        val timeMillis = System.currentTimeMillis()
        val week = TimeUtils.getChineseWeek(timeMillis).replace("周", "星期")
        binding.signDate.setText("${DateTimeUtils.getDateFont(timeMillis)} ${week}")

        initMap()

        binding.signList.setOnClickListener {
            ArouterManager.navigation(this,"/sign/SignListActivity")
        }

        vm.sendIntent(SignIntent.getSigns(SPUtils.getInstance().getInt(Const.UID)))

        //morning,2025-08-01 09:00:00
        /*val sign = SPUtils.getInstance().getString("sign", "")
        if (sign.isNotEmpty()) {
            val split = sign.split(",")
            val date = split[1].split(" ")[0]//打卡日期
            if (date == DateTimeUtils.getDate(System.currentTimeMillis())) {//说明今天打过
                if (split[0] == "morning") {//说明今天打过上班卡
                    binding.signTvdaka.text = "下班打卡"
                } else {//说明今天打过下班卡
                    binding.btnSign.isEnabled = false
                }
            }
        }*/

        binding.btnSign.setOnClickListener {
            val dateTime = DateTimeUtils.getDateTime(System.currentTimeMillis())
            var status = "正常"
            if (binding.signTvdaka.text == "上班打卡") {
//                SPUtils.getInstance().put("sign", "morning,${dateTime}")
                binding.signTvdaka.text = "下班打卡"
                if (dateTime.split(" ")[1] > "09:00:00") {
                    status = "迟到"
                }
                val item = SignBeanItem(
                    "",
                    SPUtils.getInstance().getString("loc", ""),
                    null,
                    "天津市",
                    dateTime,
                    status,
                    SPUtils.getInstance().getInt(Const.UID)
                )
                vm.sendIntent(SignIntent.addSign(item))
            } else {
//                SPUtils.getInstance().put("sign", "after,${dateTime}")
                binding.btnSign.isEnabled = false
                if (dateTime.split(" ")[1] < "18:00:00") {
                    status = "早退"
                }
                val item = SignBeanItem(
                    SPUtils.getInstance().getString("morning", ""),
                    SPUtils.getInstance().getString("loc", ""),
                    SPUtils.getInstance().getInt("sid",-1),
                    "天津市",
                    dateTime,
                    status,
                    SPUtils.getInstance().getInt(Const.UID)
                )
                vm.sendIntent(SignIntent.addSign(item))
            }
        }
    }

    private fun initMap() {
        LocationClient.setAgreePrivacy(true)
        //定位初始化
        mLocationClient = LocationClient(this)

//通过LocationClientOption设置LocationClient相关参数
        val option = LocationClientOption()
        option.isOpenGps = true // 打开gps

        option.setCoorType("bd09ll") // 设置坐标类型

        option.setScanSpan(1000)

//设置locationClientOption
        mLocationClient?.setLocOption(option)

//注册LocationListener监听器
        val myLocationListener = MyLocationListener()
        mLocationClient?.registerLocationListener(myLocationListener)
//开启地图定位图层
        mLocationClient?.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer?.cancel()
            timer = null
        }
        mLocationClient?.stop();
    }


    inner class MyLocationListener : BDAbstractLocationListener() {
        override fun onReceiveLocation(location: BDLocation) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null) {
                return
            }
            Log.i("lr", "${location.latitude}-${location.longitude}")
            if (SPUtils.getInstance().getString("loc", "").isNullOrEmpty())
                SPUtils.getInstance().put("loc", "${location.latitude},${location.longitude}")
            else
                mLocationClient?.stop()
        }
    }


}